package com.malbbmsomanagerdemo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.json.JSONStringer;
import com.malbbmsomanager.management.DM_BBM_Item_Master;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Date;

public class DM_BBM_Upload_Testing extends Activity {
	ProgressDialog mProgressDialog;
	// Database Name
	private static final String DBNAME = "dminvoicemanagerbbm.db";
	private static final String TAG = null;
	// ****Main Transaction Table****
	private String SERVER_DETAILS = "serverinfo";
	private String USER_SETTINGS = "usersettings";
	private String FORDHED_TABLE = "FOrdHed";
	private String FORDDET_TABLE = "FOrdDet";
	private String FORDTAXDT_TABLE = "FOrdTaxDt";
	private String FORDTAXRG_TABLE = "FOrdTaxRg";
	private SQLiteDatabase mydb;

	ArrayList<String> arFinvHed = new ArrayList<String>();
	ArrayList<String> arFinvDet = new ArrayList<String>();

	ArrayList<String> arFOrdTaxDt = new ArrayList<String>();
	ArrayList<String> arFOrdTaxRg = new ArrayList<String>();

	String connectionURL, currentUserServerDB;
	SimpleDateFormat originalFormatTxn = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormatTxn = new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat originalFormat = new SimpleDateFormat(
			"dd MM yyyy hh:mm:ss aa");
	SimpleDateFormat targetFormat = new SimpleDateFormat(
			"yyyy-MM-dd hh:mm:ss aa");
	Date date;
	InputStream is = null;
	StringBuilder sb = null;
	JSONStringer userJson = null;
	TextView uploadtitle,uploaduploadcount;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_upload_testing);

		getConnectionUrl();
		checkCurrentServerDB();

		Button uploadactive = (Button) findViewById(R.id.uploadactive);
		uploadtitle = (TextView) findViewById(R.id.uploadtitle);
		uploaduploadcount = (TextView) findViewById(R.id.uploaduploadcount);
		
		
		uploadactive.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				new UploadingInvoiceDataValues().execute();
			}
		});

	}

	// Retrieve Current URL
	private void getConnectionUrl() {
		// TODO Auto-generated method stub
		Cursor getserverurl = null;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			getserverurl = mydb.query(SERVER_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e) {
			Log.v(TAG, "UPLOAD EXCEPTION 1" + e);
		}
		if (getserverurl != null) {
			if (getserverurl.getCount() > 0) {
				while (getserverurl.moveToNext()) {
					connectionURL = getserverurl.getString(1);
					Log.v(TAG, "connectionURL:" + connectionURL);
				}
			}
		}
		mydb.close();
	}

	protected void checkCurrentServerDB() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectServerDB = null;
		try {
			selectServerDB = mydb.query(USER_SETTINGS, null, null, null, null,
					null, null);
		} catch (Exception e) {
			Log.v(TAG, "UPLOAD EXCEPTION 2" + e);
		}
		if (selectServerDB != null) {
			if (selectServerDB.getCount() > 0) {
				while (selectServerDB.moveToNext()) {
					currentUserServerDB = selectServerDB.getString(7);
					Log.v(TAG, "currentUserServerDB:" + currentUserServerDB);
				}
			}
		}
		selectServerDB.close();
		mydb.close();
	}

	private class UploadingInvoiceDataValues extends
			AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_BBM_Upload_Testing.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Invoice Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor selectInvHeadDetails = null;
			Cursor selectInvDetailsData = null;
			Cursor selectFOrdTaxDt = null;
			Cursor selectFOrdTaxRg = null;

			Cursor getRecordFInvHed = null;
			try {
			/*	getRecordFInvHed = mydb
						.query(FORDHED_TABLE,
								null,
								"syncHed ='0' AND Active_State !='1' AND TxnDate >= '17-07-2014'",
								null, null, null, null);*/
				getRecordFInvHed = mydb
						.query(FORDHED_TABLE,
								null, "RefNo ='OS/1407/003'",
								null, null, null, null);
			} catch (Exception e) {
				Log.v(TAG, "UPLOAD EXCEPTION 3" + e);
			}

			if (getRecordFInvHed != null) {
				if (getRecordFInvHed.getCount() > 0) {
					while (getRecordFInvHed.moveToNext()) {
						String RefNofOHedUploading = getRecordFInvHed
								.getString(1);
						//Log.v(TAG, "UPLOADING INVOICE:" + RefNofOHedUploading);

						/*********** SO Details Selection *********************/
						// *****Select Uploading Tax Details****//
						String queryfOrdHedDetails, queryfOrdDetails, queryChkTaxCode, queryChkTaxReg;
						
						try {
							queryfOrdHedDetails = "SELECT * from FOrdHed Where RefNo = '"
									+ RefNofOHedUploading + "'";
							selectInvHeadDetails = mydb.rawQuery(
									queryfOrdHedDetails, null);
						} catch (Exception e) {
							Log.v(TAG, "Exception FOrdHed :" + e);
						}

						try {
							queryfOrdDetails = "SELECT * from FOrdDet Where RefNo = '"
									+ RefNofOHedUploading + "'";
							selectInvDetailsData = mydb.rawQuery(
									queryfOrdDetails, null);
						} catch (Exception e) {
							Log.v(TAG, "Exception FOrdDet :" + e);
						}

						try {
							queryChkTaxCode = "SELECT * from FOrdTaxDt Where RefNo = '"
									+ RefNofOHedUploading + "'";
							selectFOrdTaxDt = mydb.rawQuery(queryChkTaxCode,
									null);
						} catch (Exception e) {
							Log.v(TAG, "Exception FOrdTaxDt :" + e);
						}

						try {
							queryChkTaxReg = "SELECT * from FOrdTaxRg Where RefNo = '"
									+ RefNofOHedUploading + "'";
							selectFOrdTaxRg = mydb.rawQuery(queryChkTaxReg,
									null);
						} catch (Exception e) {
							Log.v(TAG, "Exception FOrdTaxRg :" + e);
						}

						/*************************************************/
						if (selectFOrdTaxRg != null) {
							if (selectFOrdTaxRg.getCount() > 0) {
								while (selectFOrdTaxRg.moveToNext()) {
									String RefNo = selectFOrdTaxRg.getString(1)
											.trim();
									String TaxCode = selectFOrdTaxRg.getString(
											2).trim();
									String TaxRegNo = selectFOrdTaxRg
											.getString(3).trim();
									try {
										JSONObject valuesJsonFOrdTaxRg = new JSONObject();
										valuesJsonFOrdTaxRg.put("RefNo",
												RefNo.trim());
										valuesJsonFOrdTaxRg.put("TaxCode",
												TaxCode.trim());
										if (TaxRegNo.trim().length() != 0) {
											valuesJsonFOrdTaxRg.put("TaxRegNo",
													TaxRegNo.trim());
										} else {
											valuesJsonFOrdTaxRg.put("TaxRegNo",
													" ");
										}

										valuesJsonFOrdTaxRg.put("DbName",
												currentUserServerDB);
										arFOrdTaxRg.add(valuesJsonFOrdTaxRg
												.toString());
									} catch (Exception e) {
										Log.v(TAG, "UPLOAD FOrdTaxRg :" + e);
									}
								}
							}
						}

						/***********************************************************/

						if (selectFOrdTaxDt != null) {
							if (selectFOrdTaxDt.getCount() > 0) {
								while (selectFOrdTaxDt.moveToNext()) {
									String RefNo = selectFOrdTaxDt.getString(1)
											.trim();
									String ItemCode = selectFOrdTaxDt
											.getString(2).trim();
									String TaxComCode = selectFOrdTaxDt
											.getString(3).trim();
									String TaxCode = selectFOrdTaxDt.getString(
											4).trim();
									String TaxPer = selectFOrdTaxDt
											.getString(5).trim();
									String TaxRate = selectFOrdTaxDt.getString(
											6).trim();
									String Taxseq = selectFOrdTaxDt
											.getString(7).trim();
									String BTaxDetAmt = selectFOrdTaxDt
											.getString(8).trim();
									String TaxDetAmt = selectFOrdTaxDt
											.getString(9).trim();
									try {
										JSONObject valuesJsonFOrdTaxDt = new JSONObject();
										valuesJsonFOrdTaxDt.put("RefNo",
												RefNo.trim());
										valuesJsonFOrdTaxDt.put("ItemCode",
												ItemCode.trim());
										valuesJsonFOrdTaxDt.put("TaxComCode",
												TaxComCode.trim());
										valuesJsonFOrdTaxDt.put("TaxCode",
												TaxCode.trim());
										valuesJsonFOrdTaxDt.put("TaxPer",
												TaxPer.trim());
										valuesJsonFOrdTaxDt.put("TaxRate",
												TaxRate.trim());
										valuesJsonFOrdTaxDt.put("Taxseq",
												Taxseq.trim());
										valuesJsonFOrdTaxDt.put("BTaxDetAmt",
												BTaxDetAmt.trim());
										valuesJsonFOrdTaxDt.put("TaxDetAmt",
												TaxDetAmt.trim());
										valuesJsonFOrdTaxDt.put("DbName",
												currentUserServerDB);
										arFOrdTaxDt.add(valuesJsonFOrdTaxDt
												.toString());
									} catch (Exception e) {
										Log.v(TAG, "UPLOAD arFOrdTaxDt :" + e);
									}
								}
							}
						}

						/***********************************************************/
						if (selectInvHeadDetails != null) {
							if (selectInvHeadDetails.getCount() > 0) {
								while (selectInvHeadDetails.moveToNext()) {
									String RefNo = selectInvHeadDetails
											.getString(1).trim();
									String RefNo1 = selectInvHeadDetails
											.getString(2).trim();
									String TxnDate = selectInvHeadDetails
											.getString(3).trim();
									try {
										date = originalFormatTxn.parse(TxnDate
												.replaceAll("[-+/.^,]", " "));
										TxnDate = targetFormatTxn.format(date);
									} catch (ParseException ex) {
										TxnDate = "1900-01-01";
									}
									String ManuRef = selectInvHeadDetails
											.getString(4).trim();
									String CurCode = selectInvHeadDetails
											.getString(5).trim();
									String CostCode = selectInvHeadDetails
											.getString(6).trim();
									String CurRate = selectInvHeadDetails
											.getString(7).trim();
									String DebCode = selectInvHeadDetails
											.getString(8).trim();
									String Remarks = selectInvHeadDetails
											.getString(9).trim();
									String TxnType = selectInvHeadDetails
											.getString(10).trim();
									String QuoTerm = selectInvHeadDetails
											.getString(11).trim();
									String LocCode = selectInvHeadDetails
											.getString(12).trim();
									String RepCode = selectInvHeadDetails
											.getString(13).trim();
									String BTotalDis = selectInvHeadDetails
											.getString(14)
											.replaceAll("[,]", "").trim();
									String TotalDis = selectInvHeadDetails
											.getString(15)
											.replaceAll("[,]", "").trim();
									String PTotalDis = selectInvHeadDetails
											.getString(16)
											.replaceAll("[,]", "").trim();
									String BPTotalDis = selectInvHeadDetails
											.getString(17)
											.replaceAll("[,]", "").trim();
									String BTotalTax = selectInvHeadDetails
											.getString(18)
											.replaceAll("[,]", "").trim();
									String TotalTax = selectInvHeadDetails
											.getString(19)
											.replaceAll("[,]", "").trim();
									String BTotalAmt = selectInvHeadDetails
											.getString(20)
											.replaceAll("[,]", "").trim();
									String TotalAmt = selectInvHeadDetails
											.getString(21)
											.replaceAll("[,]", "").trim();
									String TaxReg = selectInvHeadDetails
											.getString(22).trim();
									String Contact = selectInvHeadDetails
											.getString(23).trim();
									String CusAdd1 = selectInvHeadDetails
											.getString(24).trim();
									String CusAdd2 = selectInvHeadDetails
											.getString(25).trim();
									String CusAdd3 = selectInvHeadDetails
											.getString(26).trim();
									String CusTele = selectInvHeadDetails
											.getString(27).trim();
									String PrtCopy = selectInvHeadDetails
											.getString(28).trim();
									String AddUser = selectInvHeadDetails
											.getString(29).trim();
									String AddDate = selectInvHeadDetails
											.getString(30).trim();
									String AddMach = selectInvHeadDetails
											.getString(31).trim();
									String disper = selectInvHeadDetails
											.getString(32)
											.replaceAll("[,]", "").trim();
									String Appsts = selectInvHeadDetails
											.getString(33).trim();
									String SellSts = selectInvHeadDetails
											.getString(34).trim();
									String AppUser = selectInvHeadDetails
											.getString(35).trim();
									String Appdate = selectInvHeadDetails
											.getString(36).trim();
									try {
										date = originalFormat.parse(Appdate
												.replaceAll("[-+/.^,]", " "));
										Appdate = targetFormat.format(date);
									} catch (ParseException ex) {
										Appdate = "2000-01-01 12:00:00.000";
									}
									String RemarkPri = selectInvHeadDetails
											.getString(37);
									String Customer_name = selectInvHeadDetails
											.getString(38);
									String Active_State = selectInvHeadDetails
											.getString(39);
									String SalesOrd_Type = selectInvHeadDetails
											.getString(40);
									String Longitude = selectInvHeadDetails
											.getString(41);
									String Latitude = selectInvHeadDetails
											.getString(42);
									String InvStartTime = selectInvHeadDetails
											.getString(43);
									String InvEndTime = selectInvHeadDetails
											.getString(44);
									String InvHedNetTotal = selectInvHeadDetails
											.getString(45);
									String syncHed = selectInvHeadDetails
											.getString(46);
									String fsoStartTime = selectInvHeadDetails
											.getString(47);
									String salesOrdEndTime = selectInvHeadDetails
											.getString(48);

									try {
										JSONObject valuesJsonFinvHed = new JSONObject();
										valuesJsonFinvHed.put("RefNo",
												RefNo.trim());
										if (RefNo1.trim().length() != 0) {
											valuesJsonFinvHed.put("RefNo1",
													Contact.trim());
										} else {
											valuesJsonFinvHed
													.put("RefNo1", " ");
										}
										valuesJsonFinvHed.put("TxnDate",
												TxnDate.trim());
										if (ManuRef.trim().length() != 0) {
											valuesJsonFinvHed.put("ManuRef",
													ManuRef.trim());
										} else {
											valuesJsonFinvHed.put("ManuRef",
													" ");
										}
										valuesJsonFinvHed.put("CurCode",
												CurCode.trim());
										valuesJsonFinvHed.put("CostCode",
												CostCode.trim());
										valuesJsonFinvHed.put("CurRate",
												CurRate);
										valuesJsonFinvHed.put("DebCode",
												DebCode.trim());
										valuesJsonFinvHed.put("Remarks",
												Remarks.trim());
										valuesJsonFinvHed.put("TxnType",
												TxnType.trim());
										valuesJsonFinvHed.put("QuoTerm",
												QuoTerm.trim());
										valuesJsonFinvHed.put("LocCode",
												LocCode.trim());
										valuesJsonFinvHed.put("RepCode",
												RepCode.trim());
										valuesJsonFinvHed.put("BTotalDis",
												BTotalDis.trim());
										valuesJsonFinvHed.put("TotalDis",
												TotalDis.trim());
										valuesJsonFinvHed.put("PTotalDis",
												PTotalDis.trim());
										valuesJsonFinvHed.put("BPTotalDis",
												BPTotalDis.trim());
										valuesJsonFinvHed.put("BTotalTax",
												BTotalTax.trim());
										valuesJsonFinvHed.put("TotalTax",
												TotalTax.trim());
										valuesJsonFinvHed.put("BTotalAmt",
												BTotalAmt.trim());
										valuesJsonFinvHed.put("TotalAmt",
												TotalAmt.trim());
										valuesJsonFinvHed.put("TaxReg", "Y");

										if (Contact.trim().length() != 0) {
											valuesJsonFinvHed.put("Contact",
													Contact.trim());
										} else {
											valuesJsonFinvHed.put("Contact",
													" ");
										}

										valuesJsonFinvHed.put("CusAdd1",
												CusAdd1.trim());
										valuesJsonFinvHed.put("CusAdd2",
												CusAdd2.trim());
										valuesJsonFinvHed.put("CusAdd3",
												CusAdd3.trim());

										if (CusTele.trim().length() != 0) {
											valuesJsonFinvHed
													.put("CusTele",
															CusTele.replaceAll(
																	"/", ""));
										} else {
											valuesJsonFinvHed.put("CusTele",
													" ");
										}

										valuesJsonFinvHed.put("PrtCopy",
												PrtCopy.trim());
										valuesJsonFinvHed.put("AddUser",
												AddUser.trim());
										valuesJsonFinvHed.put("AddDate",
												AddDate.trim());
										valuesJsonFinvHed.put("AddMach",
												AddMach.trim());
										valuesJsonFinvHed.put("disper",
												disper.trim());
										valuesJsonFinvHed.put("Appsts",
												Appsts.trim());
										valuesJsonFinvHed.put("SellSts",
												SellSts.trim());

										if (AppUser.trim().length() != 0) {
											valuesJsonFinvHed.put("AppUser",
													AppUser.trim());
										} else {
											valuesJsonFinvHed.put("AppUser",
													" ");
										}
										valuesJsonFinvHed.put("Appdate",
												Appdate.trim());
										valuesJsonFinvHed.put("RemarkPri",
												RemarkPri.trim());
										valuesJsonFinvHed.put("fsoStartTime",
												fsoStartTime.trim());
										valuesJsonFinvHed.put("fsoEndTime",
												salesOrdEndTime.trim());
										valuesJsonFinvHed.put("DbName",
												currentUserServerDB);
										arFinvHed.add(valuesJsonFinvHed
												.toString());
									} catch (Exception ex) {
										Log.v(TAG, "UPLOAD arFinvHed :" + ex);
									}

								}
							}
						}
						/******************************************************/
						if (selectInvDetailsData != null) {
							if (selectInvDetailsData.getCount() > 0) {
								while (selectInvDetailsData.moveToNext()) {
									String orddet_id = selectInvDetailsData
											.getString(0);
									String RefNo = selectInvDetailsData
											.getString(1).trim();
									String TxnDate = selectInvDetailsData
											.getString(2).trim();
									try {
										date = originalFormatTxn.parse(TxnDate
												.replaceAll("[-+/.^,]", " "));
										TxnDate = targetFormatTxn.format(date);
									} catch (ParseException ex) {
										TxnDate = "1900-01-01";
									}
									String TxnType = selectInvDetailsData
											.getString(3).trim();
									String SeqNo = selectInvDetailsData
											.getString(4).trim();
									String Itemcode = selectInvDetailsData
											.getString(5).trim();
									//Log.v(TAG, "UPLOAD DATA RECORDS : " + Itemcode);
									String Qty = selectInvDetailsData
											.getString(6).trim();
									String BalQty = selectInvDetailsData
											.getString(7).trim();
									String TaxComCode = selectInvDetailsData
											.getString(8).trim();
									String BSellPrice = selectInvDetailsData
											.getString(9).replaceAll("[,]", "");
									String SellPrice = selectInvDetailsData
											.getString(10)
											.replaceAll("[,]", "").trim();
									String BTSellPrice = selectInvDetailsData
											.getString(11)
											.replaceAll("[,]", "").trim();
									String TSellPrice = selectInvDetailsData
											.getString(12)
											.replaceAll("[,]", "").trim();
									String PrilCode = selectInvDetailsData
											.getString(13)
											.replaceAll("[,]", "").trim();
									String DisPer = selectInvDetailsData
											.getString(14)
											.replaceAll("[,]", "").trim();
									String BDisAmt = selectInvDetailsData
											.getString(15)
											.replaceAll("[,]", "").trim();
									String DisAmt = selectInvDetailsData
											.getString(16)
											.replaceAll("[,]", "").trim();
									String PDisAmt = selectInvDetailsData
											.getString(17)
											.replaceAll("[,]", "").trim();
									String BPDisAmt = selectInvDetailsData
											.getString(18)
											.replaceAll("[,]", "").trim();
									String BTaxAmt = selectInvDetailsData
											.getString(19)
											.replaceAll("[,]", "").trim();
									String TaxAmt = selectInvDetailsData
											.getString(20)
											.replaceAll("[,]", "").trim();
									String BAmt = selectInvDetailsData
											.getString(21)
											.replaceAll("[,]", "").trim();
									String Amt = selectInvDetailsData
											.getString(22)
											.replaceAll("[,]", "").trim();
									String Linkrec = selectInvDetailsData
											.getString(23).trim();
									String OrSellPrice = selectInvDetailsData
											.getString(24)
											.replaceAll("[,]", "").trim();
									String OrBSellPrice = selectInvDetailsData
											.getString(25)
											.replaceAll("[,]", "").trim();
									String OrTSellPrice = selectInvDetailsData
											.getString(26)
											.replaceAll("[,]", "").trim();
									String OrBTSellPrice = selectInvDetailsData
											.getString(27)
											.replaceAll("[,]", "").trim();
									String Packing = selectInvDetailsData
											.getString(28).trim();
									String Quopacking = selectInvDetailsData
											.getString(29).trim();
									String cases = selectInvDetailsData
											.getString(30).trim();
									String freeqty = selectInvDetailsData
											.getString(31)
											.replaceAll("[,]", "").trim();
									String balfreeqty = selectInvDetailsData
											.getString(32)
											.replaceAll("[,]", "").trim();
									String ItemName = selectInvDetailsData
											.getString(33).trim();
									ItemName = ItemName.replaceAll("\\*", "");
									ItemName = ItemName.replaceAll("&", "");
									ItemName = ItemName.replaceAll(
											"[-+.^:,//()]", "");
									String RetailPrice = selectInvDetailsData
											.getString(34)
											.replaceAll("[,]", "").trim();
									String BrandCode = selectInvDetailsData
											.getString(35).trim();
									String BrandName = selectInvDetailsData
											.getString(36).trim();
									String value = selectInvDetailsData
											.getString(37).trim();
									String totordval = selectInvDetailsData
											.getString(38).trim();
									String finalQty = selectInvDetailsData
											.getString(39).trim();
									String syncDet = selectInvDetailsData
											.getString(40).trim();

									try {
										JSONObject valuesJsonFinvDet = new JSONObject();
										valuesJsonFinvDet.put("RefNo",
												RefNo.trim());
										valuesJsonFinvDet.put("TxnDate",
												TxnDate.trim());
										valuesJsonFinvDet.put("TxnType",
												TxnType.trim());
										valuesJsonFinvDet.put("SeqNo",
												SeqNo.trim());
										valuesJsonFinvDet.put("Itemcode",
												Itemcode);
										valuesJsonFinvDet
												.put("Qty", Qty.trim());
										valuesJsonFinvDet.put("BalQty",
												BalQty.trim());
										valuesJsonFinvDet.put("TaxComCode",
												TaxComCode.trim());
										valuesJsonFinvDet.put("BSellPrice",
												BSellPrice.trim());
										valuesJsonFinvDet.put("SellPrice",
												SellPrice.trim());
										valuesJsonFinvDet.put("BTSellPrice",
												BTSellPrice.trim());
										valuesJsonFinvDet.put("TSellPrice",
												TSellPrice.trim());
										valuesJsonFinvDet.put("PrilCode",
												PrilCode.trim());
										valuesJsonFinvDet.put("DisPer",
												DisPer.trim());
										valuesJsonFinvDet.put("BDisAmt",
												BDisAmt.trim());
										valuesJsonFinvDet.put("DisAmt",
												DisAmt.trim());
										valuesJsonFinvDet.put("PDisAmt",
												PDisAmt.trim());
										valuesJsonFinvDet.put("BPDisAmt",
												BPDisAmt.trim());
										valuesJsonFinvDet.put("BTaxAmt",
												BTaxAmt.trim());
										valuesJsonFinvDet.put("TaxAmt",
												TaxAmt.trim());
										valuesJsonFinvDet.put("BAmt",
												BAmt.trim());
										valuesJsonFinvDet
												.put("Amt", Amt.trim());
										valuesJsonFinvDet.put("Linkrec",
												Linkrec.trim());
										valuesJsonFinvDet.put("RecordId",
												orddet_id.trim());
										valuesJsonFinvDet.put("OrSellPrice",
												OrSellPrice.trim());
										valuesJsonFinvDet.put("OrBSellPrice",
												OrBSellPrice.trim());
										valuesJsonFinvDet.put("OrTSellPrice",
												OrTSellPrice.trim());
										valuesJsonFinvDet.put("OrBTSellPrice",
												OrBTSellPrice.trim());
										valuesJsonFinvDet.put("Packing",
												Packing);

										if (Quopacking.trim().length() != 0) {
											valuesJsonFinvDet.put("Quopacking",
													Quopacking.trim());
										} else {
											valuesJsonFinvDet.put("Quopacking",
													" ");
										}
										valuesJsonFinvDet.put("cases",
												cases.trim());
										valuesJsonFinvDet.put("freeqty",
												freeqty.trim());
										valuesJsonFinvDet.put("balfreeqty",
												balfreeqty.trim());
										valuesJsonFinvDet.put("ItemName",
												ItemName.trim());
										valuesJsonFinvDet.put("RetailPrice",
												RetailPrice.trim());
										valuesJsonFinvDet.put("DbName",
												currentUserServerDB);
										arFinvDet.add(valuesJsonFinvDet
												.toString().replace("+", ""));
									} catch (Exception ex) {
										Log.v(TAG, "Exception" + ex);
									}
								}
							}
						}

						/***********************************************************/
						
						String strFH = arFinvHed.toString();
						String strFD = arFinvDet.toString();
						String strOrdTaxReg = arFOrdTaxRg.toString();
						String strOrdTaxDet = arFOrdTaxDt.toString();
						
						/***********************************************************/
						
					/*	if (selectInvHeadDetails.getCount() <= 0) {
							//Log.v(TAG, "ARRAY 1" + strFH + "/" + strFD);
						}
						else{*/
							strFH = strFH.replace("[", "");
							strFH = strFH.replace("]", "");
							strFD = strFD.replace("[", "");
							strFD = strFD.replace("]", "");
							strOrdTaxReg = strOrdTaxReg.replace("[", "");
							strOrdTaxReg = strOrdTaxReg.replace("]", "");
							strOrdTaxDet = strOrdTaxDet.replace("[", "");
							strOrdTaxDet = strOrdTaxDet.replace("]", "");

							// PDADBWebServiceM
							HttpPost request = new HttpPost(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/updateFOrdHed");
							
							try {
								userJson = new JSONStringer().object()
										.key("fOHed").value(strFH).key("fODet")
										.value(strFD).key("fOTaxDt")
										.value(strOrdTaxDet).key("fOTaxRg")
										.value(strOrdTaxReg);
							} catch (Exception e) {
								Log.v(TAG, "UPLOAD EXCEPTION 1" + e);
							}
							StringEntity entity = null;
							try {
								String format1 = userJson.toString().replace("[", "");
								String format2 = format1.replace("]", "");
								String format3 = format2.replace("\\", "");

								String format4 = "\"fOHed\":\"";
								String format5 = "\",\"fODet\":\"";
								String format5a = "\",\"fOTaxDt\":\"";
								String format5b = "\",\"fOTaxRg\":\"";

								String format6 = format3.replace(format4,"\"fOHed\":[");
								String format7 = format6.replace(format5,"],\"fODet\":[");
								String format8 = format7.replace(format5a,"],\"fOTaxDt\":[");
								String format9 = format8.replace(format5b,"],\"fOTaxRg\":[");
								format9 = format9 + "}";
								String dj = format9.replace("\"}\"}", "\"}]}");
								dj = dj.replaceAll("\\*", " ");
								dj = dj.trim();

								/***************************/
								Log.v(TAG, "********FULL REQUEST********\n");
								// Log.v(TAG, "JSON - Request: =" + dj);
								int maxLogSize = 1000;
								for (int i = 0; i <= dj.length() / maxLogSize; i++) {
									int start = i * maxLogSize;
									int end = (i + 1) * maxLogSize;
									end = end > dj.length() ? dj.length() : end;
									//Log.v(TAG, dj.substring(start, end));
								}
								//Log.v(TAG, "********FULL REQUEST END********\n");
								
								
								Log.v(TAG, "SERVER REQUEST LENGTH: =" + dj.length());
								Log.v(TAG, "SERVER REQUEST BYTES: =" + dj.getBytes().toString());
								Log.v(TAG, "SERVER REQUEST LENGTH: =" + dj.trim().length());
								Log.v(TAG, "SERVER REQUEST BYTES: =" + dj.trim().getBytes().toString());
								//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
								dj = dj.trim();//.toCharArray();
								
								final byte[] utf8Bytes = dj.getBytes("UTF-8");
								byte[] bytes1 = dj.getBytes();
								System.out.println("Returned  Value " + bytes1.length );
								System.out.println("Returned  Value " + utf8Bytes.length );

								final byte[] utf16Bytes= dj.getBytes("UTF-16");
								byte[] bytes2 = dj.getBytes();
								System.out.println("Returned  Value " + bytes2.length );
								System.out.println("Returned  Value " + utf16Bytes.length );

								final byte[] utf32Bytes = dj.getBytes("UTF-32");
								byte[] bytes3 = dj.getBytes();
								System.out.println("Returned  Value " + bytes3.length );
								System.out.println("Returned  Value " + utf32Bytes.length );

								final byte[] isoBytes = dj.getBytes("ISO-8859-1");
								byte[] bytes4 = dj.getBytes();
								System.out.println("Returned  Value " + bytes4.length );
								System.out.println("Returned  Value " + isoBytes.length );

								final byte[] winBytes = dj.getBytes("CP1252");
								byte[] bytes5 = dj.getBytes();
								System.out.println("Returned  Value " + bytes5.length );
								System.out.println("Returned  Value " + winBytes.length );
								
								
								
								
								entity = new StringEntity(dj, "UTF-8");
								entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
								entity.setContentType("application/json");
								request.setEntity(entity);
								// Send request to WCF service
								DefaultHttpClient httpClient = new DefaultHttpClient();
								
								try {
									Log.e("response", "connect");
									HttpResponse response = httpClient.execute(request);
									HttpEntity entitye = response.getEntity();
									is = entitye.getContent();
									if (is != null) {
										BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
										sb = new StringBuilder();
										sb.append(reader.readLine() + "\n");
										String line = "0";
										while ((line = reader.readLine()) != null) {
											sb.append(line + "\n");
										}
										is.close();
										String result = sb.toString();
										Log.v(TAG, "SERVER REPONCE 100: =" + result);
										String result1 = result.replace("\"","");
										Log.v(TAG, "SERVER REPONCE 200: =" + result1);
									}
								}
								catch(Exception e){
									Log.v(TAG, "UPLOAD EXCEPTION 2" + e);
								}
								
							}
							catch(Exception e){
								Log.v(TAG, "UPLOAD EXCEPTION 3" + e);
							}
						//}

					}
				}
			}
			return null;

		}
		
		@Override
		protected void onPostExecute(Void args) {
			arFinvHed.clear();
			arFinvDet.clear();
			arFOrdTaxRg.clear();
			arFOrdTaxDt.clear();
			mProgressDialog.dismiss();
		}
	}
}
